<!--  -->
<template>
  <div class=''>
    <el-form ref="thirdFrom" :inline="true" size="small" :model="thirdFrom" class="demo-form-inline">
      <el-form-item label="关键词搜索" prop="kw">
        <el-input v-model="thirdFrom.kw" placeholder="请输入关键词"></el-input>
      </el-form-item>
      <el-form-item label="时间范围" prop="value_flag">
        <el-date-picker
          v-model="thirdFrom.value_flag"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="getthirdListArr"
          class="queryButton"
          icon="el-icon-search">查询</el-button>
        <el-button
          class="resetButton"
          @click="resetQuery('thirdFrom')"
          icon="el-icon-refresh">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- <el-form>
      <el-button
        type="primary"
        plain
        @click="openAdd"
        class="queryButton"
        v-permissions="'thirdClient:add'"
        icon="el-icon-plus">新增</el-button>
        
      <el-button
        type="success"
        plain
        @click="downloadAPI"
        class="queryButton"
        icon="el-icon-download">下载api</el-button>
    </el-form> -->
    
    <!-- 新增信息源弹框 -->
    <el-dialog
      title="新增信息源"
      :visible.sync="isShowAdd"
      @close="closeAdd('companyForm')"
      :close-on-press-escape="true"
      :close-on-click-modal="false"
      width="30%">
      <el-form ref="companyForm" size="small" :model="clientArr" :rules="addClientRules" label-width="100px">
        <el-form-item label="信息源名称" prop="name">
          <el-input v-model="clientArr.name"></el-input>
        </el-form-item>
        <el-form-item label="公海列表" prop="seasId">
          <el-select v-model="clientArr.seasId" placeholder="请选择公海">
            <el-option
            v-for="(item,index) in seasListArr"
            :key="index"
            :label="item.seasName"
            :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="depId">
          <el-tree
            v-model="clientArr.depId"
            :data="treeArrFordepartment"
            node-key="id"
            size="small"
            :check-strictly="defaultRelev"
            @node-click="handleCheckChange"
            :props="defaultProps"
            default-expand-all
            :expand-on-click-node="false">
          </el-tree>
        </el-form-item>
      </el-form>
      <div style="width: 100%; text-align: center;">
        <el-button 
          type="primary"
          plain
          @click="submitClient"
          class="queryButton">保存</el-button>
        <el-button
          plain
          class="resetButton"
          @click="closeAdd('companyForm')">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 详情信息源弹框 -->
    <el-dialog
      title="信息源详情"
      :visible.sync="isShowDetail"
      @close="closeDetail('detailForm')"
      :close-on-press-escape="true"
      :close-on-click-modal="false"
      width="30%">
      <el-form ref="detailForm" size="small" :model="detailObj" :rules="detailRule" label-width="100px">
        <el-form-item label="信息源名称" prop="tName">
          <el-input v-model="detailObj.tName"></el-input>
        </el-form-item>
        <el-form-item label="公海列表" prop="seasId">
          <el-select v-model="detailObj.seasId" placeholder="请选择公海">
            <el-option
            v-for="(item,index) in seasListArr"
            :key="index"
            :label="item.seasName"
            :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="depId">
          <el-tree
            v-model="detailObj.depId"
            :disabled="true"
            :data="treeArrFordepartment"
            ref="detailUserTree"
            node-key="id"
            size="small"
            @node-click="handleCheckChange_de"
            :default-expanded-keys="defaultExpandedKeys"
            highlight-current
            :props="defaultProps">
          </el-tree>
        </el-form-item>
      </el-form>
      <div style="width: 100%; text-align: center;">
        <el-button 
          type="primary"
          plain
          v-permissions="'thirdClient:update'"
          @click="submitDetail"
          class="queryButton">保存</el-button>
        <el-button
          plain
          class="resetButton"
          @click="closeDetail('detailForm')">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 验证码弹框 -->
    <el-dialog
      title="验证码"
      :visible.sync="isShowVerCode"
      @close="closeVer('VerForm')"
      :close-on-press-escape="true"
      :close-on-click-modal="false"
      width="30%">
      <el-form :inline="false" ref="VerForm" size="small" :model="verObj" :rules="verRule" label-width="100px">
        <el-form-item label="验证码" prop="verVal">
          <el-input v-model="verObj.verVal"><span @click="getVerCode" slot="append">获取验证码</span></el-input>
        </el-form-item>
      </el-form>
      <div style="width: 100%; text-align: center;">
        <el-button 
          type="primary"
          plain
          @click="submitVer"
          class="queryButton">保存</el-button>
        <el-button
          plain
          class="resetButton"
          @click="closeVer('VerForm')">关闭</el-button>
      </div>
    </el-dialog>
    <el-table
      :data="tableData"
      :header-cell-style="{ background:'#f8f8f9',color:'#515a6e'}"
      size="mini"
      style="width: 100%; margin-top: 5px;">
      <el-table-column
        type="index"
        label="序号"
        width="50">
      </el-table-column>
      <el-table-column
        prop="cusId"
        label="用户ID"
        width="90">
        <template slot-scope="scope">
          <span>{{ scope.row.cusId == null ? '-' : scope.row.cusId }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="userName"
        label="用户名"
        width="90">
      </el-table-column>
      <el-table-column
        prop="cusName"
        label="客户名称"
        width="90">
        <template slot-scope="scope">
          <span>{{ scope.row.cusName == null ? '-' : scope.row.cusName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="cusPhone"
        label="客户电话"
        width="90">
        <template slot-scope="scope">
          <span>{{ scope.row.cusPhone == null ? '-' : scope.row.cusPhone }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间">
        <template slot-scope="scope">
          <span>{{ timestampToDate(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        width="200"
        :show-overflow-tooltip="true"
        label="key">
        <template slot-scope="scope">
          <span>{{ !scope.row.checked ? '************' : scope.row.tKey }}</span>
          <i class="el-icon-view" style="margin-left: 3px;" @click.stop="changeStatus(scope.row,scope.$index)"></i>
          <i class="el-icon-refresh" v-permissions="'thirdClient:refreshKey'" style="margin-left: 3px;" @click.stop="refreshCode(scope.row,scope.$index)"></i>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleForceLogout(scope.row)"
          >详情</el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <pagination
      class="pagination_container"
      :total="paginationForOut.total"
      :page-sizes="[10, 20, 50, 100]"
      :page.sync="paginationForOut.page"
      :limit.sync="paginationForOut.pageSize"
      @pagination="getthirdListArr"
    />
  </div>
</template>

<script>
import { callRecordRecordList,thirdClientAdd,thirdClientUpdate,thirdClientRefreshKey } from '@/request/callRecord';
import { departmentList } from '@/request/departmentUser';
import { seasList } from '@/request/seas';

import { timestampToDate } from '@/until/paramRou'
import { smsRefreshKey } from '@/request/login';
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
    data() {
    //这里存放数据
      return {
        seasListArr: [],
        currentID: '',
        defaultExpandedKeys: [],
        // end
        // 部门树图
        departmentArr: null,
        treeArrFordepartment: [],
        defaultCheckRole: [],
        setRoleIdArrFir: [],
        setRoleIdArrSen: [],
        defaultRelev: false,
        defaultProps: {
          children: 'childList',
          label: 'depName'
        },
        submitParentId: null,
        updateSubmitParentId: null,
        // end
        isShowVerCode: false,
        isShowDetail: false,
        isShowAdd: false,
        paginationForOut: {
          page: 1,
          pageSize: 10,
          total: 20
        },
        thirdFrom: {
          kw: '',
          value_flag: []
        },
        clientArr: {
          name: '',
          seasId: '',
          depId: ''
        },
        addClientRules: {
          name: [
            { required: true, trigger: 'blur', message: '请输入您的信息源名称' }
          ],
          seasId: [
            { required: true, trigger: 'change', message: '请选择公海' }
          ],
          depId: [
            { required: true, trigger: 'change', message: '请选择部门' }
          ]
        },
        detailRule: {
          tName: [
            { required: true, trigger: 'blur', message: '请输入您的信息源名称' }
          ],
          seasId: [
            { required: true, trigger: 'change', message: '请选择公海' }
          ],
          depId: [
            { required: true, trigger: 'change', message: '请选择部门' }
          ]
        },
        detailObj: {

        },
        tableData: [],
        verObj: {
          verVal: ''
        },
        verCode: '',
        verRule: {
          verVal: [
            { required: true, trigger: 'blur', message: '请输入验证码' }
          ],
        },
      };
    },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {

    // 获取公海列表
    getSeasList(){
      seasList().then(res => {
        if (res.code === '200') {
          this.seasListArr = res.data
        }
      })
    },
    // 获取部门列表
    getDepartmentList(){
      departmentList().then(res => {
        if (res.code === '200') {
          if (res.data != null) {
            this.remenberDepartMentID = res.data.id
            const nullArr = []
            nullArr.push({
              depName: res.data.name,
              id: res.data.id,
              childList: JSON.parse(JSON.stringify(res.data.departmentList)),
              my_tagID: 998
            })
            this.departmentArr = res.data
            this.treeArrFordepartment = nullArr
          }
          
        } else {
          this.treeArrFordepartment = []
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      }).catch(err => {
        this.$message({
          message: '服务器忙~',
          type: 'warning'
        })
      })
    },
    // tree fun 选择左侧部门 获取用户列表
    handleCheckChange(data){
      data.parentId === undefined ? this.clientArr.depId = 0 : this.clientArr.depId = data.id
    },
    handleCheckChange_de(data){
      data.parentId === undefined ? this.detailObj.depId = 0 : this.detailObj.depId = data.id
    },
    closeVer(name){
      // this.resetForm(name)
      this.$refs[name].resetFields();
      this.isShowVerCode = false
      this.getthirdListArr()
    },
    submitVer(){
      this.$refs.VerForm.validate((valid) => {
        if (valid) {
          let obj = {
            clientId: this.verCode,
            validCode: this.verObj.verVal
          }
          thirdClientRefreshKey(obj).then(res => {
            if (res.code === '200') {
              this.$message({
                type: 'success',
                message: '操作成功'
              })
              this.closeVer('VerForm')
              this.getthirdListArr()
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          }).catch(err => {
            this.$message({
              message: '服务器忙~',
              type: 'warning'
            })
          })
        }
      })
    },
    // 获取验证码
    getVerCode(){
      smsRefreshKey().then(res => {
        if (res.code === '200') {
          this.$message({
            type: 'success',
            message: '验证码发送成功'
          })
        } else {
          this.$message({
            type: 'error',
            message: '验证码发送失败'
          })
        }
      }).catch(err => {
        this.$message({
          message: '服务器忙~',
          type: 'warning'
        })
      })
    },
    // 下载api
    downloadAPI(){
      // window.location.href= `${this.$configURL}download/third_ad.zip`
      window.location.href= `http://81.70.133.172/download/third_ad.zip`
    },
    refreshCode(item){
      this.isShowVerCode = true
      this.verCode = item.tId
    },

    // 显示信息源key
    changeStatus(item,index){
      this.tableData[index].checked ? this.tableData[index].checked = false : this.tableData[index].checked = true
    },
    // 获取信息源列表
    getthirdListArr(){
      let obj = {}
      if (this.thirdFrom.value_flag === null) {
        obj = {
          kw: this.thirdFrom.kw,
          startTime: '',
          endTime: '',
          limit: this.paginationForOut.pageSize,
          page: this.paginationForOut.page,
        }
      } else {
        obj = {
          kw: this.thirdFrom.kw,
          startTime: timestampToDate(this.thirdFrom.value_flag[0]) === 'NaN-aN-aN' ? '' : timestampToDate(this.thirdFrom.value_flag[0]),
          endTime: timestampToDate(this.thirdFrom.value_flag[1]) === 'NaN-aN-aN' ? '' : timestampToDate(this.thirdFrom.value_flag[1]),
          limit: this.paginationForOut.pageSize,
          page: this.paginationForOut.page,
        }
      }
      callRecordRecordList(obj).then(res => {
        if (res.code === '200') {
          for (const element of res.data.records) {
            element.checked = false
          }
          this.tableData = res.data.records
          if (res.data.total > 0 && Math.ceil(res.data.total / this.paginationForOut.size) < this.paginationForOut.page) {
            this.paginationForOut.page = Math.ceil(res.data.total / this.paginationForOut.size)
            this.getthirdListArr()
          } else {
            this.paginationForOut.total = res.data.total
          }
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      }).catch(err => {
        this.$message({
          message: '服务器忙~',
          type: 'warning'
        })
      })
    },
    // 关闭信息源弹框
    closeAdd(name){
      this.isShowAdd = false
      // this.resetForm(name)
      this.$refs[name].resetFields();
    },
    // 打开信息源弹框
    openAdd(){
      this.isShowAdd = true
    },
    // 保存新增
    submitClient(){
      this.$refs.companyForm.validate((valid) => {
        if (valid) {
          thirdClientAdd(this.clientArr).then(res => {
            if (res.code === '200') {
              this.isShowAdd = false
              this.getthirdListArr()
              this.$message({
                type: 'success',
                message: '操作成功'
              })
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          }).catch(err => {
            this.$message({
              message: '服务器忙~',
              type: 'warning'
            })
          })
        }
      })
    },
    // 打开详情
    handleForceLogout(val){
      this.detailObj = val
      this.currentID = val.depId
      this.$nextTick(() => {
        this.$refs.detailUserTree.setCurrentKey(this.currentID);
        this.expandParentNodes(this.currentID);
      });
      this.isShowDetail = true
    },
    expandParentNodes(nodeId) {
      // console.log(nodeId);
      
      const node = this.$refs.detailUserTree.getNode(nodeId);
      if (node.parent && node.parent.level !== 0 && node.parent.data.parentId !== undefined) {
        this.defaultExpandedKeys.push(node.parent.data.id);
        this.expandParentNodes(node.parent.data.id);
      }
      // 去重并更新展开状态
      this.defaultExpandedKeys = [...new Set(this.defaultExpandedKeys)];
      // this.$refs.detailUserTree.store.setExpandedKeys(this.defaultExpandedKeys); // 选择打开
    },
    // 保存详情
    submitDetail(){
      this.$refs.detailForm.validate((valid) => {
        if (valid) {
          const obj = {
            clientId: this.detailObj.tId,
            name: this.detailObj.tName,
            depId: this.detailObj.depId,
            seasId: this.detailObj.seasId
          }
          thirdClientUpdate(obj).then(res => {
            if (res.code === '200') {
              this.isShowDetail = false
              this.getthirdListArr()
              this.$message({
                type: 'success',
                message: '操作成功'
              })
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          }).catch(err => {
            this.$message({
              message: '服务器忙~',
              type: 'warning'
            })
          })
        }
      })
    },
    closeDetail(name){
      this.isShowDetail = false
      // this.resetForm(name)
      this.$refs[name].resetFields();
      this.getthirdListArr()
    },
    resetQuery(fromName) {
      // this.resetForm(fromName)
      this.$refs[fromName].resetFields();
      this.getthirdListArr()
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {

  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getthirdListArr()
    // this.getSeasList()
    // this.getDepartmentList()
  },
}
</script>
<style lang='scss' scoped>
  //@import url(); 引入公共css类
</style>
